package com.shihan.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @Description
 * @Author shihan
 * @Date 2020/8/9 15:59
 * @Version 1.0
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //之前编码时写入过一个int型，4个字节来表示长度；
        if(byteBuf.readableBytes() < 4){
            return;
        }
        //标记一下当前的 readIndex 位置
        byteBuf.markReaderIndex();
        //读取传送过来的消息长度； readInt 方法会让 readIndex 加 4
        int dataLength = byteBuf.readInt();

        if(byteBuf.readableBytes() < dataLength){
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] data = new byte[dataLength];

        byteBuf.readBytes(data);
        Object object = serializer.deserialize(clazz, data);
        list.add(object);

    }
}
